package cn.bellychang.leetcode.question387;

import java.util.LinkedHashMap;

/**
 * Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
 *
 * Note: You may assume the string contains only lowercase English letters.
 *
 * @author ChangLiang
 * @date 2021/2/6
 */
public class Solution {

    public int firstUniqChar(String s) {

        // 将其放到linkedHashMap中
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (map.keySet().contains(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }

        for (int i = 0; i < chars.length; i++) {
            if (map.get(chars[i]) == 1) {
                return i;
            }
        }

        return -1;
    }
}
